






new Vue({
    el: "#app",
    data() {
        return {
            userId: "",
            queryFormVisible :false,
            addFormVisible: false,
            queryForm : {},
            addForm:{},

            queryFormLabelWidth: 120,
            addFormLabelWidth:120,

            pickerOptions: {
                shortcuts: [{
                  text: '最近一周',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                  }
                }, {
                  text: '最近一个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                  }
                }, {
                  text: '最近三个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                  }
                }]
              },
        }
    },
    methods: {
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    },
    // 查询
    query(){
        startDate = this.formatDate(this.queryForm.dates[0])
        endDate = this.formatDate(this.queryForm.dates[1])
        this.getWeight(startDate,endDate)

    },


    // 添加
    add(){
        let _this = this
        let weight = {}
        weight["userId"]= this.userId
        weight["date"] = this.formatDate(this.addForm.date)
        if(this.addForm.time == "morning"){
            weight["morningWeight"] = this.addForm.weight
        }else{
            weight["eveningWeight"] = this.addForm.weight
        }


        axios({
            method: "POST",
            url: "http://localhost:8080/weight/add",
            data: weight,
          }).then(function (resp) {
            console.log(typeof (resp.data.code))
            if (!(resp.data.code == 200)) {
              _this.$message({
                message: resp.data.message,
                type: 'error'
              });
            } else {
              _this.addForm={}
              _this.addFormVisible = false
              date = _this.getTodayAndSevenDaysAgo()
              _this.getWeight(date.startDate,date.endDate)
      
            }
          })



    },

    // 获取数据
      getWeight( startDate, endDate){
        var _this = this;
        axios({
            method: "GET",
            url: "http://localhost:8080/weight/get/"+_this.userId+"/"+startDate+"/"+endDate
          }).then(function (resp) {
            console.log(typeof (resp.data.code))
            if (!(resp.data.code == 200)) {
              _this.$message({
                message: resp.data.message,
                type: 'error'
              });
            } else {
              _this.queryForm={}
              _this.drawWeightChart(resp.data.data)
              _this.queryFormVisible = false
            }
          })
        },

  
      // 绘制体重图
      drawWeightChart(data) {
  
        // 初始化ECharts实例
        var myChart = echarts.init(document.getElementById('main'));
        var minWeight = data.minWeight
        var maxWeight = data.maxWeight
        var interval = data.intervalWeight
        var morningWeights = data.morningWeights
        var eveningWeights = data.eveningWeights
        var avgWeights = data.avgWeights
        var diffWeights = data.diffWeights
        var dates = data.dates
         // 美化后的配置项
        var option = {
            title: {
              text: '每日体重变化图',
              subtext: '记录体重变化以及每日差异',
              left: 'center',
              textStyle: {
                color: '#333',
                fontSize: 24
              }
            },
            tooltip: {
              trigger: 'axis',
              backgroundColor: 'rgba(0, 0, 0, 0.7)',
              textStyle: {
                color: '#fff'
              }
            },
            legend: {
              data: ['早上体重', '晚上体重', '平均体重', '体重差'],
              top: '10%',
              textStyle: {
                color: '#333'
              }
            },
            grid: {
              left: '10%',
              right: '10%',
              bottom: '15%',
              top: '20%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: dates, // 填入日期数据
              axisLabel: {
                interval: 0,
                rotate: 45,
                color: '#333'
              },
              axisLine: {
                lineStyle: {
                  color: '#ccc'
                }
              },
              axisTick: {
                show: false
              }
            },
            yAxis: [
              {
                type: 'value',
                name: '体重 (斤)',
                position: 'left',
                axisLine: {
                  lineStyle: {
                    color: '#008c8c'
                  }
                },
                axisLabel: {
                  formatter: '{value} 斤',
                  color: '#008c8c' // 改变字体颜色
                },
                min: minWeight, // 调整y轴的最小值
                max: maxWeight, // 调整y轴的最大值
                interval: interval,
                splitLine: {
                  lineStyle: {
                    color: '#eee'
                  }
                }
              },
              {
                type: 'value',
                name: '体重差 (斤)',
                position: 'right',
                axisLine: {
                  lineStyle: {
                    color: '#f29c11'
                  }
                },
                axisLabel: {
                  formatter: '{value} 斤',
                  color: '#f29c11' // 改变字体颜色
                },
                splitLine: {
                  show: false
                }
              }
            ],
            series: [
              {
                name: '早上体重',
                type: 'line',
                data: morningWeights, // 体重数据用斤表示
                smooth: true,
                itemStyle: {
                  color: '#2f89fc'
                },
                areaStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0, color: 'rgba(47, 137, 252, 0.2)' // 0% 处的颜色
                    }, {
                      offset: 1, color: 'rgba(47, 137, 252, 0)' // 100% 处的颜色
                    }]
                  }
                },
                lineStyle: {
                  width: 3 // 设置线条宽度
                }
              },
              {
                name: '晚上体重',
                type: 'line',
                data: eveningWeights, // 体重数据用斤表示
                smooth: true,
                itemStyle: {
                  color: '#b4e1f1'
                },
                areaStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0, color: 'rgba(180, 225, 241, 0.2)' // 0% 处的颜色
                    }, {
                      offset: 1, color: 'rgba(180, 225, 241, 0)' // 100% 处的颜色
                    }]
                  }
                },
                lineStyle: {
                  width: 3 // 设置线条宽度
                }
              },
              {
                name: '平均体重',
                type: 'line',
                data: avgWeights, // 体重数据用斤表示
                smooth: true,
                itemStyle: {
                  color: '#c05e74'
                },
                lineStyle: {
                  type: 'dashed',
                  width: 3 // 设置线条宽度
                },
                areaStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0, color: 'rgba(192, 94, 116, 0.1)' // 0% 处的颜色
                    }, {
                      offset: 1, color: 'rgba(192, 94, 116, 0)' // 100% 处的颜色
                    }]
                  }
                }
              },
              {
                name: '体重差',
                type: 'bar',
                data: diffWeights, // 体重差
                yAxisIndex: 1,
                itemStyle: {
                  color: '#f29c11'
                },
                barWidth: '10%', // 调整柱状图宽度
                label: {
                  show: true,
                  position: 'top',
                  color: '#333'
                }
              }
            ],
            animationDuration: 1000,
            animationEasing: 'cubicInOut'
          };
      
          myChart.setOption(option);
          window.addEventListener('resize', () => myChart.resize());
      },

      // 切换用户
      switchUser(){
        window.location.href = "login.html"
      },

     
      getTodayAndSevenDaysAgo() {
        const today = new Date();
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(today.getDate() - 30); // 包含今天，总共30天
      
        const format = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        };
      
        return {
          startDate: format(sevenDaysAgo),
          endDate: format(today)
        };
      },

        // 获取uri中的参数
        getValue(name) {
          var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
          var r = window.location.search.substr(1).match(reg);  //匹配目标参数
          if (r != null) return unescape(r[2]); return null; //返回参数值
      }
  
    },
  
    mounted() {
        this.userId = this.getValue("id")
        // 获取最近30天的日期
        date = this.getTodayAndSevenDaysAgo()
        this.getWeight(date.startDate,date.endDate)

    }
  })
  
  
  